package cn.zhejianglao.shirotemplate.common;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class CommonUtils {
    /**
     * 将汉字转换为全拼
     *
     * @param text 文本
     * @return 全拼
     */
    public static String getPinyin(String text) {
        char[] chars = text.toLowerCase().toCharArray();
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        // 设置大小写
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        // 设置声调表示方法
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        // 设置字母u表示方法
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        String[] s;
        String rs = StringUtils.EMPTY;
        try {
            StringBuilder sb = new StringBuilder();
            for (char aChar : chars) {
                // 判断是否为汉字字符
                if (String.valueOf(aChar).matches("[\\u4E00-\\u9FA5]+")) {
                    s = PinyinHelper.toHanyuPinyinStringArray(aChar, format);
                    if (s != null) {
                        sb.append(s[0]);
                        continue;
                    }
                }
                sb.append(aChar);
            }
            rs = sb.toString();
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            log.error("获取拼音出错： " + e.getMessage());
        }
        return rs;
    }
}
